package com.hhh.bigevent.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hhh.bigevent.pojo.CategoryDO;
import com.hhh.bigevent.pojo.Result;
import com.hhh.bigevent.utils.ThreadLocalUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hehehe
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @GetMapping
    public Result<List<CategoryDO>> list() {
        List<CategoryDO> categoryDOS = new CategoryDO().selectList(Wrappers.lambdaQuery(CategoryDO.class).eq(CategoryDO::getCreateUser, ThreadLocalUtil.getUserId()));
        return Result.success(categoryDOS);
    }

    @PostMapping
    public Result<Boolean> add(@RequestBody @Validated CategoryDO categoryDO) {
        boolean b = categoryDO.setCreateUser(ThreadLocalUtil.getUserId()).setUpdateTime(LocalDateTime.now()).setCreateTime(LocalDateTime.now()).insert();
        return Result.success(b);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(CategoryDO.Update.class) CategoryDO categoryDO) {
        CategoryDO aDo = categoryDO.selectById();
        if (aDo == null) {
            return Result.error("操作失败！这个文章分类不存在！");
        }
        if (!aDo.getCreateUser().equals(ThreadLocalUtil.getUserId())) {
            return Result.error("操作失败！这个文章分类不属于你！");
        }
        boolean b = categoryDO.setUpdateTime(LocalDateTime.now()).updateById();
        return Result.success(b);
    }

    @GetMapping("/detail")
    public Result<CategoryDO> detail(@RequestParam("id") Integer id) {
        CategoryDO categoryDO = new CategoryDO().setId(id).selectById();
        return Result.success(categoryDO);
    }

    @DeleteMapping
    public Result delete(@RequestParam("id") Integer id) {
        CategoryDO aDo = new CategoryDO().setId(id).selectById();
        if (aDo == null) {
            return Result.error("操作失败！这个文章分类不存在！");
        }
        if (!aDo.getCreateUser().equals(ThreadLocalUtil.getUserId())) {
            return Result.error("操作失败！这个文章分类不属于你！");
        }
        boolean b = new CategoryDO().setId(id).deleteById();
        return Result.success(b);
    }

}
